package com.rajaev.dtu.tractor.infrastructure.interceptors;

import com.rajaev.dtu.tractor.infrastructure.base.errors.BusinessException;
import com.rajaev.dtu.tractor.infrastructure.base.errors.ErrorCodes;
import com.rajaev.dtu.tractor.infrastructure.helper.MD5ValueGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;

@Component
public class OpenApiInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //判断签名和随机数是否存在
        if (StringUtils.isEmpty(request.getParameter("signature")) ||
                StringUtils.isEmpty(request.getParameter("nonceStr"))) {
            throw new BusinessException(ErrorCodes.ERR_AUTH_INFO);
        }

        checkSignature(request);
        return true;

    }

    private void checkSignature(HttpServletRequest request) throws BusinessException {

        Map<String, String[]> values = request.getParameterMap();
        StringBuilder sb = new StringBuilder();

        values.forEach((key, value) -> {
            if (!key.equalsIgnoreCase("signature")) {
                sb.append(value[0]);
            }
        });

        String s = sb.toString();
        byte[] bytes = s.getBytes();
        Arrays.sort(bytes);

        if(!MD5ValueGenerator.generateValue(new String(bytes)).equalsIgnoreCase(request.getParameter("signature"))){
           throw  new BusinessException(ErrorCodes.ERR_AUTH_INFO);
        }

    }


}
